/*
 * station-details.js
 * 站点详情页面
 */
;
(function (call) {
	var main = {
		baseUrl: CafeJS.CXT,
		router: {
			getForecastChartData: CafeJS.CXT + 'analysis/getForecastChartData.do',
			getLatestTime: CafeJS.CXT+'/analysis/getModelLatestTime.do'
		},
		seriesColors: ['#00bbee', '#ee0000', '#ee8800', '#44bb55', '#dd00dd'],
		tableHeader: { category: '预报时间', tp: '降水(mm)', tmp: '温度(℃)', ws: '风速(m/s)', wd: '风向'/*, rh: '相对湿度(%)', tcc: '云量(%)'*/ },
		chartData: null,
		init: function () {
			this.getLatestTime();
			this.initView();
			this.bindEvt();
		},
		// 获取最新起报时间
        getLatestTime: function() {
        	var that = this;
        	var modeType = "ECMF";
        	var pcode = 'TMP2M-' + modeType;
        	var param = {
        		pcode: pcode,
        		area: 'AFSH',
        		height: 0
        	};
        	$.ajax({
        		url: this.router.getLatestTime,
        		type: 'GET',
        		dataType: 'json',
        		async: false,
        		data: param
        	}).done(function(res){
        		if (res.success) {
        			var latestTime = dateUtil.convertStringToDate7(res.params.data,'yyyy-MM-dd hh:mm');
        			$("#dateSeq").val(latestTime);
        			$.IDate(".date-panelSeq", {
						query: function query() {
							gridDetail.initView();
						}
					});
        		}
        	})
        },
		initView: function () {
			var that = this;
			var location = $("#param").data('location');
			var model = $('.selection option:selected').val();
			var modelNm = $('.selection option:selected').text();
			var baseDate = $("#dateSeq").IDatePicker().getVal() + ":00";
			var queryTime = new Date(baseDate).format('yyyyMMddhhmmss');
			//location.lon = '121.78';
			//location.lat = '31.05';
			var param = {
				queryTime: queryTime,
				lon: location.lon,
				lat: location.lat,
				model: model
			}
			$.getJSON(this.router.getForecastChartData, param, function (res) {
				if (res.success) {
					that.chartData = res.params.data;
					that._bulidTableInfo();
					that._bulidChartInfo();
					var statNm = that.chartData.station.statnm
					$(".grid-detail-title").html([modelNm, ' 时序图[经度：', location.lon, ' 纬度：', location.lat, '][临近站：', statNm, ']'].join(''));
				}
			})
		},
		// 展示时序表格
		_bulidTableInfo: function () {
			var that = this;
			var $header = $('.grid-detail-header table').empty();
			var $body = $('.grid-detail-body table').empty();
			var prevDay, index = [];
			$.each(that.tableHeader, function (key, val) {
				$header.append(`<tr><td>${val}</td></tr>`);
				var $tr = $('<tr>');
				if (key == 'category') {
					var data = that.chartData[key];
					if (!data) return;
					data.forEach(function (d, i) {
						var dateTime = new Date(d);
						var day = dateTime.format('dd');
						if (prevDay == day)
							$tr.append(`<td><p></p><p>${dateTime.format('hh:mm')}</p></td>`);
						else {
							var style = '';
							if (i > 0) {
								index.push(i);
								style = 'border-left:2px;border-left-style:solid;border-left-color:#e4e4e1';
							}
							$tr.append(`<td><p style=${style}>${day}日</p><p style=${style}>${dateTime.format('hh:mm')}</p></td>`);
						}
						prevDay = day;
					})
				} else {
					var data = that.chartData.data[key];
					if (!data) return;
					var $tr = $('<tr>');
					data.forEach(function (val, i) {
						var $td = $('<td>');
						$td.html(val);
						if (i < 13) {
							$td.css({'background-color':'#f4c887'});
						}
						if (index.indexOf(i) != -1) {
							$td.css({'border-left':'2px','border-left-style':'solid','border-left-color':'#e4e4e1'});
						}
						$tr.append($td);
					})
				}
				$body.append($tr);
			})
		},
		// 生成时序chart图
		_bulidChartInfo: function () {
			var that = this;
			var oldDay;
			var newData = {};
			var seriesData = [], seriesKey = [], categories = that.chartData.category;

			$.each(that.tableHeader, function (k, n) {
				if (k == 'category') return;
				if (k.indexOf('wd') == -1)
					seriesKey.push(k);
			})
			categories.forEach(function (d, i) {
				categories[i] = new Date(d).getTime();
			})
			$.each(that.chartData.data, function (k, n) {
				newData[k] = [];
				$.each(n, function (i, j) {
					if (i >= 13)
					newData[k].push([categories[i], j == '' ? null : Number(j)]);
				})
			})
			seriesKey.forEach(function (item, index) {
				if (!newData[item]) return;
				if (item.indexOf('ws') != -1) { // 风向标
					var wdData = [];
					var wdName = item.replace('ws', 'wd');
					newData[wdName].forEach(function (wd, i) {
						var wdIcon = WindUtil.getWindDire(WindUtil.calcWindDire(wd[1])).EN;
						wdData.push({
							x: newData[item][i][0],
							y: newData[item][i][1],
							marker: {
								symbol: 'url(../business/monitor/common/css/images/wind/' + wdIcon + '.png)'
							}
						})
					});
					newData[item] = wdData;
				}
				seriesData.push({
					name: that.tableHeader[item],
					type: ['tp'].indexOf(item) != -1 ? 'column' : 'spline',
					yAxis: index,
					visible: index > 2 ? false : true,
					marker: { enabled: true, radius: 3 },
					data: newData[item]
				})
			})
			var trendChart = {
				title: null,
				chart: {
					backgroundColor: 'transparent'
				},
				rangeSelector: {
					enabled: false
				},
				scrollbar: {
					height: 0
				},
				credits: {
					enabled: false
				},
				exporting: {
					enabled: false
				},
				navigator: {
					height: 25,
					margin: 2,
					xAxis: {
						labels: {
							format: '{value: }'
						}
					}
				},
				tooltip: {
					shared: true,
					useHTML: true,
					headerFormat: '<b>{point.key}</b><br/>',
					xDateFormat: '%Y-%m-%d %H:%S'
				},
				legend: {
					enabled: true,
					verticalAlign: 'top',
					itemStyle: { 'fontSize': '14px', 'fontWeight': 'normal' }
				},
				plotOptions: {
					series: {
						connectNulls: true,
						marker: {
							symbol: 'circle'
						}
					}
				},
				colors: that.seriesColors,
				xAxis: {
					lineColor: '#333',
					tickColor: '#333',
					tickPositions: categories,
					labels: {
						useHTML: true,
						step: 2,
						style: { 'textAlign': 'center' },
						formatter: function () {
							var date = new Date(this.value).format('yyyy-MM-dd hh').split(" ");
							var ymd = date[0].split("-");
							if (oldDay != ymd[2]) {
								oldDay = ymd[2];
								return date[1] + "<br/><span style='color:#006dda;'>" + ymd[2] + "日</span>";
							} else {
								return date[1];
							}
						}
					}
				},
				yAxis: [
					{
						labels: { style: { color: that.seriesColors[0] } },
						opposite: false,
						offset: -5,
						//tickInterval: 0.5,
						min: 0
					},
					{
						labels: { style: { color: that.seriesColors[1] } },
						opposite: false,
						//tickInterval: 3,
						offset: 15,
					},
					{
						labels: { style: { color: that.seriesColors[2] } },
						offset: -5,
						//tickInterval: 0.5,
						min: 0
					},
					{
						labels: { style: { color: that.seriesColors[3] } },
						offset: 20,
						//tickInterval: 20,
						min: 0
					},
					{
						labels: { style: { color: that.seriesColors[4] } },
						offset: 45,
						//tickInterval: 20,
						min: 0
					}
				],
				series: seriesData
			};
			Highcharts.setOptions({
				global: {
					useUTC: false
				}
			})
			Highcharts.stockChart('gridChart', trendChart);
		},
		bindEvt: function () {
			var that = this;
			$('.date-panelSeq').off('click').on('click', '.btn-forward', function (e) { // 日期向前
				e.stopPropagation();
				$("#dateSeq").IDatePicker().toForward();
				that.initView();
			}).on('click', '.btn-backward', function (e) { // 日期向后
				e.stopPropagation();
				$("#dateSeq").IDatePicker().toBackward();
				that.initView();
			}).on('click', ".btn-search", function (e) { // 搜索
				e.stopPropagation();
				that.initView();
			}).on('click', ".btn-newest", function (e) { // 最新
				e.stopPropagation();
				$("#dateSeq").IDatePicker().toNewest();
				that.initView();
			});
		}
	};
	window.gridDetail = main;
	if (typeof call === 'function') {
		call(main);
	}

})(function (main) {
	CafeJS.models(['datepicker'], function () {
		main.init();
	});
});